package com.sdry.config;

import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.sdry.exception.BizException;
import com.sdry.exception.CommonEnum;
import com.sdry.system.entity.SysUser;
import com.sdry.untils.JwtUtil;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.servlet.OncePerRequestFilter;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description 自定义过滤器
 * @Author chenBin
 * @Date 2020-03-24 15:03
 * @Version 1.0
 **/
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    /**需要拦截的地址**/
    private static final String API_URL = "/api";
    @Override
    protected void doFilterInternal(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
        HttpServletRequest request = ((HttpServletRequest) servletRequest);
        HttpServletResponse response = ((HttpServletResponse) servletResponse);
        String token = null;
        try {
            if (request.getRequestURI().contains(API_URL)){
                token = request.getParameter("token");
                //存在
                token.split("");
            }
        }catch (Exception e) {
            throw new BizException(CommonEnum.SIGNATURE_NOT_TOKE);
        }
        if (token != null) {
            try {
                //检查jwt令牌, 如果令牌不合法或者过期, 里面会直接抛出异常, 下面的catch部分会直接返回
                JwtUtil.verity(token);
            } catch (JWTDecodeException e) {
                throw  new BizException(CommonEnum.SIGNATURE_NOT_MATCH);
            }catch (TokenExpiredException e){
                throw new BizException(CommonEnum.SIGNATURE_GI_TOKE);
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        //放行
        filterChain.doFilter(request, response);
    }
}
